package com.example.robertluozizhao.java.reflect;


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author luo_zi_zhao
 * @version V1.0 反射基本使用
 * @FileName com.example.robertluozizhao.java.reflect
 * @date 2019/11/23 10:45
 */

public class BaseUseage {

    public static void main(String[] args) {

        try {
            Class clazz = Class.forName("com.example.robertluozizhao.java.reflect.Apple");

            /**
             * 1 构造创建对象
             */
            //有参
            Constructor declaredConstructor = clazz.getDeclaredConstructor(float.class, String.class,String.class);
            Object object = declaredConstructor.newInstance(4.2f, "苹果","...");
            //无参
//            Object object = clazz.newInstance();
            System.out.println(object.toString());

            /**
             * 2 字段获取/修改
             */
            Field field = clazz.getDeclaredField("area");
            Field field1 = clazz.getSuperclass().getDeclaredField("name");
            Field field2 = clazz.getSuperclass().getDeclaredField("price");
            field.setAccessible(true);
            field1.setAccessible(true);
            field2.setAccessible(true);
            field.set(object, "广东");
            field1.set(object, "梨子");
            field2.set(object, 5.8f);
            System.out.println(object.toString());

            /**
             * 3 获取方法/修改/调用
             */
            Method method = clazz.getSuperclass().getDeclaredMethod("setPrice", float.class);
            method.invoke(object, 6.4f);//修改父类价格
            Method method1 = clazz.getSuperclass().getDeclaredMethod("getName");
            Object method1Result = method1.invoke(object);//获取父类名字
            System.out.print("name:" + method1Result + ",toString:" + object.toString());



        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
